//
//  MBRechargeController.m
//  LiveBroadcast
//
//  Created by 肖剑 on 2019/3/16.
//  Copyright © 2019 moonBroadcast. All rights reserved.
//充值

#import "MBRechargeController.h"
#import <ViewDeck/ViewDeck.h>
#import "MBBaseTabbarController.h"
#import <AlipaySDK/AlipaySDK.h>
@interface MBRechargeController ()
@property (weak, nonatomic) IBOutlet UIButton *rechargeBtn;
@property (weak, nonatomic) IBOutlet UILabel *moneyLbl;
@property (assign,nonatomic)NSInteger currentTag;
@property (copy,nonatomic)NSString *chargeMoneyStr;
@end

@implementation MBRechargeController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.rechargeBtn.layer.cornerRadius = 22.0f;
    self.moneyLbl.text = self.accoutModel.accUsrInfo.fishCoins;

    [self chargeClick:(UIButton *)[self.view viewWithTag:106]];
}

// 金额
- (IBAction)chargeClick:(UIButton *)sender {
    
    UIButton *button = (UIButton *)[self.view viewWithTag:self.currentTag];
    sender.backgroundColor = self.rechargeBtn.backgroundColor;
    if(self.currentTag > 100)button.backgroundColor = [UIColor whiteColor];
    self.currentTag = sender.tag;
    if (sender.tag == 10500) {
        UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"请输入金额" message:nil preferredStyle:UIAlertControllerStyleAlert];
        [alertVC addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
            textField.placeholder = @"输入金额";
            textField.keyboardType = UIKeyboardTypeNumberPad;
            [textField becomeFirstResponder];
        }];
        [alertVC addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            [self chargeClick:(UIButton *)[self.view viewWithTag:106]];
        }]];
        [alertVC addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
            [[alertVC.textFields lastObject] resignFirstResponder];
            self.chargeMoneyStr = [alertVC.textFields lastObject].text;
            [sender setTitle:[NSString stringWithFormat:@"%@元（%@鱼币）",self.chargeMoneyStr,self.chargeMoneyStr] forState:UIControlStateNormal];
            NSLog(@"sender.tag = %@",self.chargeMoneyStr);

        }]];
        [self presentViewController:alertVC animated:YES completion:nil];
    }else{
        NSString *tempStr = [NSString stringWithFormat:@"%zd",sender.tag];
        self.chargeMoneyStr = [tempStr substringFromIndex:2];
    }
    NSLog(@"sender.tag = %@",self.chargeMoneyStr);

}
// 充值
- (IBAction)chargingClick {
    
    
    [MBHttpRequset requestWithUrl:kTradeid_userCenter_rmbBuyfishCoins setParams:@{@"userId":self.accoutModel.accUsrInfo.uId,@"money":self.chargeMoneyStr,@"payWay":@"2"} isShowProgressView:NO success:^(id  _Nonnull AJson) {
        
        NSLog(@"kTradeid_pay_alipayRequest = %@",AJson);
        [MBHttpRequset requestWithUrl:kTradeid_pay_alipayRequest setParams:@{@"outTradeNo":AJson[@"orderNo"],@"payType":@"1"} isShowProgressView:NO success:^(id  _Nonnull AJson) {
            NSLog(@"kTradeid_pay_alipayRequest = %@",AJson);
            CGFloat money = [self.accoutModel.accUsrInfo.fishCoins floatValue] + [self.chargeMoneyStr floatValue];
            self.moneyLbl.text = [NSString stringWithFormat:@"%.2f",money];
            [self AliPay:AJson];
        } failure:^(id  _Nonnull AJson) {
            
        }];
    } failure:^(id  _Nonnull AJson) {
        
    }];
    
}

- (void)AliPay:(NSString *)key
{
    // 重要说明
    // 这里只是为了方便直接向商户展示支付宝的整个支付流程；所以Demo中加签过程直接放在客户端完成；
    // 真实App里，privateKey等数据严禁放在客户端，加签过程务必要放在服务端完成；
    // 防止商户私密数据泄露，造成不必要的资金损失，及面临各种安全风险；
    /*============================================================================*/
    /*=======================需要填写商户app申请的===================================*/
    /*============================================================================*/
    NSString *appID = @"2019021463212882";
    
    // 如下私钥，rsa2PrivateKey 或者 rsaPrivateKey 只需要填入一个
    // 如果商户两个都设置了，优先使用 rsa2PrivateKey
    // rsa2PrivateKey 可以保证商户交易在更加安全的环境下进行，建议使用 rsa2PrivateKey
    // 获取 rsa2PrivateKey，建议使用支付宝提供的公私钥生成工具生成，
    // 工具地址：https://doc.open.alipay.com/docs/doc.htm?treeId=291&articleId=106097&docType=1
    NSString *rsa2PrivateKey = key;
    NSString *rsaPrivateKey = @"";
    /*============================================================================*/
    /*============================================================================*/
    /*============================================================================*/
    
    //partner和seller获取失败,提示
    if ([appID length] == 0 ||
        ([rsa2PrivateKey length] == 0 && [rsaPrivateKey length] == 0))
    {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示"
                                                                       message:@"缺少appId或者私钥,请检查参数设置"
                                                                preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *action = [UIAlertAction actionWithTitle:@"知道了"
                                                         style:UIAlertActionStyleDefault
                                                       handler:^(UIAlertAction *action){
                                                           
                                                       }];
        [alert addAction:action];
        [self presentViewController:alert animated:YES completion:^{ }];
        return;
    }
        
        // NOTE: 调用支付结果开始支付
        [[AlipaySDK defaultService] payOrder:key fromScheme:@"alipay" callback:^(NSDictionary *resultDic) {
            NSString *resultS = resultDic[@"result"];
            if (resultS.length == 0) {
                [MBProgressHUD showError:resultDic[@"memo"]];
            }
            NSLog(@"reslut = %@",resultDic);
        }];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
